<template>
  <div class="pageOut">
    <div class="pageIn">
      <el-form :inline="true" :model="formSearch" size="small">
        <el-form-item>
          <el-input
            v-model="formSearch.menu_name"
            placeholder="商品名称"
            clearable
          ></el-input>
        </el-form-item>
        <!-- <el-form-item>
          <el-date-picker
            value-format="yyyy-MM-dd"
            v-model="formSearch.time"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          >
          </el-date-picker>
        </el-form-item> -->
        <el-form-item>
          <el-button icon="el-icon-search" @click="search">查询</el-button>

          <el-button
            icon="el-icon-plus"
            v-if="permission.add"
            type="primary"
            @click="handleAdd"
            >添加</el-button
          >
        </el-form-item>
      </el-form>
      <el-table
        border
        ref="table"
        :height="height - 170"
        :data="tableData"
        :header-cell-style="{ background: '#FAFAFA', color: '#606266' }"
        v-loading="loading"
        element-loading-background="rgba(255, 255, 255, 0.5)"
        style="width: 100%"
      >
        <el-table-column
          prop="name"
          :show-overflow-tooltip="tooltip"
          label="商品名称"
        ></el-table-column>
        <el-table-column prop="goodsType" label="商品分类"></el-table-column>

        <el-table-column prop="mainPicture" label="图片" align="center">
          <template slot-scope="scope">
            <div class="img" style="cursor: pointer">
              <viewer>
                <img
                  :src="scope.row.mainPicture"
                  alt
                  :onerror="errImg"
                  title="查看高清图片"
                  style="width: 40px; height: 40px; border-radius: 50%"
                />
              </viewer>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="sellingPrice" label="价格"></el-table-column>
        <el-table-column prop="specifications" label="规格"> </el-table-column>
        <el-table-column prop="stock" label="库存数"></el-table-column>
        <el-table-column label="是否推荐">
          <template> 是 </template>
        </el-table-column>

        <el-table-column label="操作" width="320" align="center">
          <template slot-scope="scope">
            <el-button
              type="danger"
              size="mini"
              @click="handleDel(scope.row.id)"
              v-show="permission.del"
              >取消推荐</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="pageSizes"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        ></el-pagination>
      </div>

      <el-dialog
        title="选择产品"
        :visible.sync="goodsDialog"
        @close="tableClose"
        width="70%"
      >
        <div style="display: flex">
          <div style="width: 55%; margin-right: 40px">
            <el-form :inline="true" :model="dialogSearch" size="small">
              <el-form-item>
                <el-cascader
                  v-model="dialogSearch.merchant_id"
                  :props="casProps"
                  :options="casOptions"
                  clearable
                ></el-cascader>
              </el-form-item>
              <el-form-item>
                <el-input
                  v-model="dialogSearch.name"
                  placeholder="商品名称"
                  clearable
                ></el-input>
              </el-form-item>

              <el-form-item>
                <el-button icon="el-icon-search" @click="getGoodsSel"
                  >查询</el-button
                >
              </el-form-item>
            </el-form>
            <el-table
              height="400"
              ref="multipleTable"
              :data="cleckData"
              tooltip-effect="dark"
              style="width: 100%"
              @select-all="selectAll"
              @selection-change="handleSelectionChange"
            >
              <el-table-column type="selection" width="55"> </el-table-column>

              <el-table-column label="图片">
                <template slot-scope="scope">
                  <img
                    :src="scope.row.mainPicture"
                    style="width: 40px"
                    height="40px"
                    alt=""
                  />
                </template>
              </el-table-column>
              <el-table-column
                prop="name"
                label="商品名称"
                show-overflow-tooltip
              >
              </el-table-column>
              <el-table-column
                prop="sellingPrice"
                label="价格"
                show-overflow-tooltip
              >
              </el-table-column>
            </el-table>
            <!-- <div class="pageBox">
              <el-pagination
                @current-change="dailogHandleSizeChange"
                background
                layout="prev, pager, next"
                :total="dialogTotal"
              >
              </el-pagination>
            </div> -->
          </div>
          <div class="selectRightBox">
            <div class="boxTitle">
              <span>已选择的推荐商品</span>&nbsp;&nbsp;({{
                recommendList.length
              }}/4)
            </div>
            <!-- {{ recommendList.length }} -->

            <div v-if="cleckData.length > 0 && recommendList.length > 0">
              <div
                class="tableRowBox"
                v-for="(item, index) in recommendList"
                :key="index"
              >
                <!-- {{item}} -->
                <img
                  :src="item.mainPicture"
                  width="60px"
                  height="60px"
                  alt=""
                />
                <div class="texthidden" style="width: 45%">{{ item.name }}</div>
                <span style="color: red">{{ item.sellingPrice }}</span>
                <i class="el-icon-close iconBox" @click="delTable(item)"></i>
              </div>
            </div>
            <!-- <div v-else>222</div> -->
          </div>
        </div>

        <span slot="footer" class="dialog-footer">
          <el-button @click="goodsDialog = false">取 消</el-button>
          <el-button type="primary" @click="goodsClick">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import {
  goodsList,
  cancelRecommend,
  bannerAdd,
  MAIN,
  typeList,
  recommendId,
  recommendSelList,
} from "../../utils/api";
import UploadImage from "../../components/UploadImage";
import UploadImg from "../../components/UploadImg";
import Editor from "../../components/Editor";
export default {
  name: "RecommendGoods",
  props: ["height"],
  components: {
    UploadImg,
    UploadImage,
    Editor,
  },
  data() {
    return {
      recommendList: [],
      dialogTotal: 0,
      goodsDialog: false,
      options: {
        type: "picture-card",
        limit: 5,
      }, //上传图片配置项
      goodsRow: [],

      casOptions: [],
      casProps: {
        value: "id",
        label: "name",
        children: "child",
      },
      tableData: [
        {
          id: 1,
        },
      ],
      cleckData: [],
      tooltip: true, //内容过长被隐藏时显示 tooltip
      loading: true, //显示加载表格
      pageSize: 10, //每页多少条
      currentPage: 1, //当前第几页
      pageSizes: [10, 20, 30, 40, 50], //每页选择条数
      total: 0, //共多少条
      permission: {
        add: false,
        edit: false,
        del: false,
      }, //权限
      errImg: 'this.src="' + require("../../../static/img/user.png") + '"',
      formSearch: {
        merchant_id: "",
        menu_name: "",
      }, //搜索
      userinfo: {},
      casOptions: [],
      doaPageNumber: 1,
      casProps: {
        value: "id",
        label: "name",
        children: "child",
      },

      //编辑弹窗
      visible: false,
      confirmLoading: false,
      type: "",
      currentRow: {}, //当前行数据信息
      ruleForm: {}, //添加和修改的表单
      dialogSearch: {
        name: "",
        merchant_id: "",
      },

      merchant: {}, //商家列表
      cate: {}, //商品分类列表
    };
  },

  mounted() {
    this.getResource();

    this.cateSelects(); //商品分类列表
    // this.getGoodsSel();
  },
  methods: {
    selectAll() {},
    getGoodsSel() {
      let params = {
        name: this.dialogSearch.name,
        goodsTypeTwo: this.dialogSearch.merchant_id[1] || "",
        pageSize: 1000,
        pageNumber: this.doaPageNumber,
      };
      this.postRequest(recommendSelList, params, MAIN).then((res) => {
        if (res.code === 200) {
          this.cleckData = res.data.list;
          this.recommendList = res.data.recommend;
          this.dialogTotal = res.data.count;

          if (this.cleckData.length == 0) {
            this.recommendList = [];
            return;
          }
          setTimeout(() => {
            res.data.recommend.forEach((v) => {
              let index = this.cleckData.findIndex((item) => {
                return v.id == item.id;
              });
              if (index != -1) {
                this.$refs.multipleTable.toggleRowSelection(
                  this.cleckData[index],
                  true
                );
              }
            });
          }, 200);
          // console.log(this.recommendList);
        }
      });
    },
    tableClose() {
      this.recommendList = [];
      this.cleckData = [];
      this.dialogSearch = {
        name: "",
        merchant_id: "",
      };
      this.$refs.multipleTable.toggleAllSelection(false);
    },
    dailogHandleSizeChange(val) {
      this.doaPageNumber = val;
      this.getGoodsSel();
    },
    //富文本框
    onEditorChange(e) {
      this.ruleForm.rotation_images = e;
    },
    casHandleChange() {},
    // 商品分类列表
    cateSelects() {
      this.postRequest(typeList, MAIN).then((res) => {
        if (res.code == 200) {
          this.casOptions = res.data;
        }
      });
    },
    handleSelectionChange(selection) {
      if (selection.length < 5) {
        this.goodsRow = selection;
        this.recommendList = selection;
      } else {
        // this.$refs.multipleTable.clearSelection();
        // toggleRowSelection
        for (let i = 0; i < selection.length; i++) {
          if (i > 3) {
            this.$refs.multipleTable.toggleRowSelection(selection[i], false);
          }
        }
        // return this.$notify.error("只能推荐4个商品");
      }
    },
    // 取消推荐
    delTable(row) {
      this.$refs.multipleTable.toggleRowSelection(row, false);
    },
    // 推荐商品
    goodsClick() {
      let arrId = [];
      this.recommendList.forEach((v) => {
        arrId.push(v.id);
      });
      this.postRequest(recommendId, {
        goodsId: arrId.join(","),
        userId: this.userinfo.id,
      }).then((res) => {
        if (res.code === 200) {
          this.$notify.success(res.msg);
          this.goodsDialog = false;
          this.getData();
        }
      });
    },
    //获取权限资源
    getResource() {
      // console.log(this.$route.name);
      this.loading = true;
      const userinfo = JSON.parse(sessionStorage.getItem("userInfo")); //解密,获取用户登录信息
      this.userinfo = userinfo;
      let arr = userinfo.menu_id.split(",");
      // console.log(arr)
      // 新增 117
      // 取消推荐 118

      if (arr.indexOf("117") > -1) {
        this.permission.add = true;
      }

      if (arr.indexOf("118") > -1) {
        this.permission.del = true;
      }

      this.getData();
    },

    // 商品分类列表
    cateSelects() {
      this.postRequest(typeList, MAIN).then((res) => {
        if (res.code == 200) {
          this.casOptions = res.data;
        }
      });
    },

    //获取初始数据
    getData() {
      this.loading = true;
      let params = {
        userId: this.userinfo.id,
        name: this.formSearch.menu_name,
        pageNumber: this.currentPage,
        pageSize: this.pageSize,
        isRecommend: 1,
      };
      this.postRequest(goodsList, params, MAIN).then((res) => {
        if (res.code == 200) {
          this.tableData = res.data.list;
          this.total = res.data.count;
          this.loading = false;
          this.$nextTick(() => {
            //避免表格表头样式错乱
            if (this.$refs.table) this.$refs.table.doLayout();
          });
        }
      });
    },

    //分页
    handleSizeChange(val) {
      //每页 ${val} 条
      this.pageSize = val;
      this.getData();
    },
    handleCurrentChange(val) {
      //当前页
      this.currentPage = val;
      this.getData();
    },
    //查询
    search() {
      this.getData();
    },
    //新增
    handleAdd() {
      this.type = "add";
      this.currentRow = {};
      this.goodsDialog = true;
      this.getGoodsSel();
    },

    goMenuSku(row) {
      this.$router.push({
        path: "/MenuSkuList",
      });
    },
    //删除
    handleDel(id) {
      let parm = {
        id: id,
        userId: this.userinfo.id,
      };
      this.$confirm("确认取消?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.postRequest(cancelRecommend, parm, MAIN).then((res) => {
            if (res.code == 200) {
              this.$notify({
                title: "操作成功",
                message: res.msg,
                type: "success",
              });
              this.getData();
              this.getGoodsSel();
            }
          });
        })
        .catch(() => {});
    },

    // 关闭弹框
    onCancel(formName) {
      this.$refs[formName].resetFields();
      this.goodsRow = [];
      this.onReset();
    },
  },
};
</script>

<style scoped>
/deep/ .el-input-group__append,
.el-input-group__prepend {
  background-color: #1890ff;
  color: #fff;
  cursor: pointer;
}
.formInput {
  width: 300px;
}
.pageBox {
  width: 100%;
  margin-top: 30px;
  display: flex;
  justify-content: center;
}
/deep/ .el-input--mini .el-input__inner {
  height: 32px;
  line-height: 32px;
}
/deep/ input::-webkit-outer-spin-button,
/deep/ input::-webkit-inner-spin-button {
  -webkit-appearance: none;
}
/deep/ input[type="number"] {
  -moz-appearance: textfield;
}
.selectRightBox {
  border: 1px solid gray;
  border-radius: 4px;
  width: 40%;
  height: 100%;
  min-height: 500px;
  position: relative;
}
.boxTitle span {
  font-weight: bold;
  font-size: 18px;
}
.boxTitle {
  position: absolute;
  top: -54px;
}
/deep/ .el-upload-list--picture-card .el-upload-list__item {
  width: 121px;
  height: 121px;
}
.tableRowBox {
  display: flex;
  width: 85%;
  justify-content: space-between;
  align-items: center;
  font-size: 17px;
  margin: 20px;
}
.iconBox {
  color: red;
  font-size: 25px;
  font-weight: bold;
  cursor: pointer;
}
/deep/ .el-upload--picture-card {
  width: 121px;
  height: 121px;
  line-height: 130px;
}
.texthidden {
  line-height: 20px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2; /*想省略几行就写几*/
  -webkit-box-orient: vertical;
}
</style>
